import numpy as np
from numpy.linalg import LinAlgError

'''
5. 设计一个方法，可以随机生成n × n的对称正定矩阵（非对角阵）
 1.随机生成一个矩阵A
 2.B=A*At
 3.C=B+Bt
 4.判断C是否可以转为 lower-triangular，不报错就是对称正定的
 B.T The transposed array.Same as ``self.transpose()``
'''


def getP(dim):
    while 1:
        A = np.random.rand(dim, dim)
        B = np.dot(A, A.transpose())
        C = B+B.T  # makesure symmetric
        try:
            # test whether C is definite,if there is no error, C is definite
            np.linalg.cholesky(C)
            return C
        except ValueError:
            pass
        except LinAlgError:
            pass


dim = 3
P = getP(dim)
print(P)
